import React, {Component} from 'react';

import {
    AppRegistry,
    Modal,
    StyleSheet,
    Switch,
    Text,
    TouchableHighlight,
    View,
    ListView,
    TouchableOpacity,
    DeviceEventEmitter,
    Alert,
    Image,
    ScrollView,
    Dimensions,
} from 'react-native';
import StyleUtils from "../res/styles/StyleUtils";
import ViewUtils from "./ViewUtils";
import CommonUtils from "../common/CommonUtils";
import I18n from "../res/language/i18n";

let width = Dimensions.get('window').width;
let height = Dimensions.get('window').height;

let isNullChildren = [];

export default class AddToCartModal extends Component {
    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 != row2,
        });

        let length = props.attrsData ? props.attrsData.length : -1;
        let _goodsItemClickIndex = [];
        for (let i = 0; i < length; i++) {
            _goodsItemClickIndex.push({itemPosition: -1, itemValue: '',})
        }
        this.state = {
            visible: this.props.visible,
            userInfo: null,
            goodsNumber: 1,
            country: '',
            selectedIndex: -1,
            dataSource: ds,
            goodsItemClickIndex: _goodsItemClickIndex,
            isNullChildrenData: [],
            listViewPosition: -1,
        }
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((userInfo) => {

                CommonUtils.getAcyncInfo('country_iso')
                    .then((result) => {
                        this.setState({
                            country: result,
                            userInfo: JSON.parse(userInfo)
                        })
                    });
            })
    }

    /**
     * 刷新props
     * @param nexProps
     */
    componentWillReceiveProps(nexProps) {

        if (this.props.attrsData !== nexProps.attrsData) {
            let length = nexProps.attrsData.length;
            let _goodsItemClickIndex = [];
            for (let i = 0; i < length; i++) {
                _goodsItemClickIndex.push({itemPosition: -1, itemValue: '',})
            }
            this.setState({
                goodsItemClickIndex: _goodsItemClickIndex,
            })
        }
        this.setState({
            visible: nexProps.visible,
        });
    }


    /**
     * 产品的数量
     * */
    goodsNumber(isPlus) {
        let _goodsNumber = this.state.goodsNumber;
        if (isPlus) {
            _goodsNumber++;
        } else {
            if (_goodsNumber > 1)
                _goodsNumber--;
        }
        this.setState({
            goodsNumber: _goodsNumber
        })
    }


    _renderGoodsItemsRow(rowData, rowID, isColor, callBack, listViewPosition) {
        let _width = width / 5;
        let goodsItemClickIndex = this.state.goodsItemClickIndex[listViewPosition];
        let isSelect = this.state.goodsItemClickIndex.length > 0 && goodsItemClickIndex.itemPosition === rowID;
        //可不可以点击


        let select = true;
        let length = this.state.isNullChildrenData.length;
        let text = isColor ? rowData.split('|')[0] : rowData;
        for (let i = 0; i < length; i++) {
            if (this.state.isNullChildrenData[i] === text) {
                select = false
            }
        }


        return (
            <TouchableOpacity
                onPress={() => select ? callBack(isColor ? rowData.split('|')[0] : rowData, rowID) : null}
                style={[{alignItems: 'center'}]}>

                <View style={[{
                    width: _width,
                }, StyleUtils.center]}>

                    <View style={{
                        borderWidth: isSelect ? 2 : 1,
                        borderColor: isSelect ? '#333333' : '#cdcdcd',
                    }}>

                        {isColor ?
                            <View
                                style={{width: 36, height: 36, backgroundColor: rowData.split('|')[1]}}
                            />
                            :
                            <Text style={[StyleUtils.smallFont, {
                                width: _width - 24,
                                textAlign: 'center',
                                padding: 4,
                                color: select ? '#333333' : '#afafaf'
                            }]}>{text}</Text>
                        }

                    </View>
                </View>
                {isColor ? <Text
                        numberOfLines={2}
                        style={[{
                            fontSize: 12,
                            padding: 4,
                            color: select ? '#333333' : '#afafaf',
                            width: '100%',
                            textAlign: 'center'
                        }, StyleUtils.smallFont]}>{text}</Text> :
                    null}

            </TouchableOpacity>
        )
    }


    /**
     *s颜色||组合。。。
     * */
    renderAttrs(_goodsInfo) {
        let dataBlob = this.props.attrsData;
        let children = this.props.childrenData;
        if (!dataBlob || !children) return;


        //获取children里面的attr_value
        let childrenAttValues = '';

        let childrenAttDataArray = [];
        isNullChildren = [];
        for (let i = 0; i < children.length; i++) {
            if (!children[i].products) {//没有产品的属性
                isNullChildren.push(children[i].attr_value)
            }

            let attrValues = children[i].attr_value.split(',');
            childrenAttDataArray.push(attrValues);
            for (let i1 = 0; i1 < attrValues.length; i1++) {
                if (childrenAttValues.indexOf(attrValues[i1]) === -1) {
                    childrenAttValues += attrValues[i1] + ',';
                }
            }
        }


        childrenAttValues = childrenAttValues.substring(0, childrenAttValues.length - 1);

        return <ScrollView
            style={{maxHeight: height / 2}}>
            {dataBlob.map((item, i) => {

                if (!dataBlob[i]) return;
                let resultAttrsValue = [];
                let _dataSource = dataBlob[i].attr_values;
                if (dataBlob[i].is_color !== 1) {//不是颜色的话
                    _dataSource = dataBlob[i].attr_values.split(',');


                    let strings = childrenAttValues.split(',');
                    for (let i = 0, childrenValueLen = strings.length; i < childrenValueLen; i++) {

                        for (let attsI = 0, len = _dataSource.length; attsI < len; attsI++) {
                            if (strings[i] === _dataSource[attsI]) {
                                resultAttrsValue.push(_dataSource[attsI])
                            }
                        }
                    }

                    _dataSource = resultAttrsValue;

                } else {//颜色


                    let strings = childrenAttValues.split(',');
                    for (let i = 0, childrenValueLen = strings.length; i < childrenValueLen; i++) {
                        for (let attsI = 0, len = _dataSource.length; attsI < len; attsI++) {
                            let splitElement = _dataSource[attsI].split('|')[0];
                            if (strings[i] === splitElement) {
                                resultAttrsValue.push(_dataSource[attsI])
                            }
                        }
                    }

                    _dataSource = resultAttrsValue;

                }

                return <View style={{paddingBottom: 16, paddingLeft: 4}}>
                    <Text style={[StyleUtils.text, StyleUtils.smallFont, {
                        padding: 8,
                        paddingLeft: 10,
                        textAlign: 'left'
                    }]}>{dataBlob[i].attr_name} ：</Text>
                    <ListView
                        contentContainerStyle={styles.gridListStyle}
                        dataSource={this.state.dataSource.cloneWithRows(_dataSource)}
                        renderRow={(rowData, sectionID, rowID) => this._renderGoodsItemsRow(rowData, rowID, dataBlob[i].is_color === 1,
                            (_clickData, index) => this.onItemAttr(_clickData, childrenAttDataArray, index, i), i)}
                    />
                </View>
            })}
        </ScrollView>
    }


    /**
     *颜色||组合。。。。点击
     * */
    onItemAttr(_clickData, childrenAttDataArray, index, listViewIndx) {

        /**
         ["红色", "1号"]
         ["红色", "2号"]
         ["红色", "3号"]
         ["红色", "4号"]
         */

        /**
         * 处理没有数据的属性不能点击效果
         * @type {Array}
         */
        let resultArrayElement = this.state.isNullChildrenData;
        for (let i = 0, len = childrenAttDataArray.length; i < len; i++) {
            let arrayElement = childrenAttDataArray[i];
            if (arrayElement.length <= 1) {
                break
            }

            for (let i1 = 0, len1 = arrayElement.length; i1 < len1; i1++) {
                if (arrayElement[i1] === _clickData) {

                    let _resultArrayElement = arrayElement[0];
                    for (let i2 = 1, len2 = arrayElement.length; i2 < len2; i2++) {
                        _resultArrayElement = _resultArrayElement + ',' + arrayElement[i2]
                    }

                    //点击的是没有数据的item
                    for (let i3 = 0, len3 = isNullChildren.length; i3 < len3; i3++) {
                        if (_resultArrayElement === isNullChildren[i3]) {
                            resultArrayElement = _resultArrayElement.split(',');
                            for (let i4 = 0, len4 = resultArrayElement.length; i4 < len4; i4++) {
                                if (resultArrayElement[i4] === _clickData) {
                                    resultArrayElement.splice(i4, 1)
                                }
                            }
                            break;
                        } else {

                            let isNotNull = false;
                            for (let i5 = 0, len5 = arrayElement.length; i5 < len5; i5++) {
                                if (arrayElement[i5] === resultArrayElement[0]) {
                                    isNotNull = true;
                                    break
                                }
                            }
                            if (isNotNull) {
                                resultArrayElement = ''
                            }
                        }
                    }
                    break;
                }
            }
        }

        let _restltItemClickIndex = this.state.goodsItemClickIndex;
        _restltItemClickIndex[listViewIndx].itemPosition = index;
        _restltItemClickIndex[listViewIndx].itemValue = _clickData;

        this.setState({
            goodsItemClickIndex: _restltItemClickIndex,
            listViewPosition: listViewIndx,
            isNullChildrenData: resultArrayElement,
        });


        let isCheck = true;
        let length = _restltItemClickIndex.length;
        for (let i = 0; i < length; i++) {
            if (_restltItemClickIndex[i].itemPosition === -1) {
                isCheck = false;
                break;
            }
        }


        //颜色和steam
        if (isCheck) {
            let _resultValue = '';
            for (let i = 0; i < length; i++) {
                _resultValue = _resultValue + _restltItemClickIndex[i].itemValue + ','
            }
            _resultValue = _resultValue.substring(0, _resultValue.length - 1);

            this.updateProduct(_resultValue)
        }
    }


    updateProduct(attr_value) {
        let children = this.props.childrenData;
        for (let i = 0, len = children.length; i < len; i++) {
            if (children[i].attr_value === attr_value) {
                this.props.updateProduct(children[i].products)
            }
        }
    }

    /**
     * 点击ADD TO CART
     * */
    submit() {
        let clickIndex = this.state.goodsItemClickIndex;
        let length = clickIndex.length;
        if (length <= 0) {
            this.props.submit(this.state.goodsNumber);
            return;
        }


        let isCheck = true;//判断是否选择（颜色/组合。。。。。）
        for (let i = 0; i < length; i++) {
            if (clickIndex[i].itemPosition === -1) {
                isCheck = false;
                break;
            }
        }

        if (isCheck) {
            this.props.submit(this.state.goodsNumber)
        } else {
            Alert.alert(
                '',
                I18n.t('default.selectFeature'),
                [
                    {text: 'OK', style: 'cancel'},
                ],
                {cancelable: true});
        }
    }


    render() {

        let _goodsInfo = this.props.dataSource;

        return (
            <Modal
                onRequestClose={() => this.props.onRequestClose()}
                animationType={'slide'}
                transparent={true}
                visible={this.state.visible}
            >
                <TouchableHighlight
                    underlayColor={'rgba(0, 0, 0, 0.3)'}
                    onPress={() => this.props.onRequestClose()}
                    style={[StyleUtils.flex, StyleUtils.center, {justifyContent: 'flex-end',}, styles.boxStyle]}>


                    <View style={[styles.listBoxStyle]}>

                        {/*close btn*/}
                        <View style={[StyleUtils.center, StyleUtils.rowDirection]}>
                            <Text style={[StyleUtils.flex, StyleUtils.smallFont, {
                                marginLeft: 14,
                                color: 'black',
                                fontSize: 18,
                                textAlign: 'left'
                            }]} numberOfLines={1}>{I18n.t('default.selectFeature')}</Text>
                            {ViewUtils.getImageBtnView({
                                    padding: 8,
                                    alignSelf: 'flex-end',
                                    margin: 8
                                }, require('../res/images/ic_close.png'),
                                [StyleUtils.tabIconSize, {tintColor: '#333333'}],
                                () => {
                                    this.props.onRequestClose()
                                },
                                '#ebebeb')}
                        </View>

                        {/**goods items||goods colors*/}
                        {this.renderAttrs(_goodsInfo)}

                        <View style={[StyleUtils.center, {padding: 16, paddingTop: 0}]}>

                            {/**goods number*/}
                            <View style={[styles.listBoxStyle, {marginBottom: 12}]}>
                                <Text
                                    style={[StyleUtils.smallFont, {textAlign: 'left'}]}>{I18n.t('default.number')}</Text>
                            </View>

                            <View
                                style={[StyleUtils.justifySpace, StyleUtils.labelBorder, {width: '100%',}]}>
                                {/**reduce*/}
                                <TouchableOpacity
                                    onPress={() => this.goodsNumber(false)}
                                    style={{padding: 14}}>
                                    <Image
                                        style={[StyleUtils.tabIconSize]}
                                        source={require('../res/images/ic_reduce.png')}
                                    />
                                </TouchableOpacity>
                                <Text style={StyleUtils.smallFont}>{this.state.goodsNumber}</Text>

                                {/**plus*/}
                                <TouchableOpacity
                                    onPress={() => this.goodsNumber(true)}
                                    style={{padding: 14}}>

                                    <Image
                                        style={[StyleUtils.tabIconSize]}
                                        source={require('../res/images/ic_add.png')}
                                    />
                                </TouchableOpacity>
                            </View>

                            <View style={styles.btnBox}>
                                {ViewUtils.getButton(this.props.isAddToCart ? I18n.t('default.addToCart') : I18n.t('b.autoOrder'), () => this.submit())}
                            </View>
                        </View>


                    </View>
                </TouchableHighlight>
            </Modal>
        )
    }
}
const styles = StyleSheet.create({
    boxStyle: {
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },

    listBoxStyle: {
        backgroundColor: 'white',
        width: '100%',
    },
    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },

    titleStyle: {
        color: 'white',
        position: 'absolute',
    },
    selectStyle: {
        borderWidth: 1,
        borderColor: '#333333',

    },
    btnBox: {
        width: '100%',
        marginTop: 30,
        backgroundColor: 'rgba(255, 255, 255, 0.88)',
    },
});
